package com.chatdating.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class BaiduIdCardService {

    private static final String API_KEY = "vS9mdxHoAeufS1s6UVr6e527";
    private static final String SECRET_KEY = "NkljtybgXnLCWrbSabotrtEA2qYeRvbw";
    private static final String GET_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private static final String OCR_IDCARD_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";

    // 获取 Access Token
    public String getAccessToken() throws IOException {
        String getUrl = GET_TOKEN_URL + "?grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(getUrl);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> map = mapper.readValue(result, Map.class);
                return (String) map.get("access_token");
            }
        }
        return null;
    }

    // 调用百度OCR接口识别身份证图像
    public Map<String, Object> identifyIdCard(String accessToken, String imageBase64, String idCardSide) throws IOException {
        String url = OCR_IDCARD_URL + "?access_token=" + accessToken;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置正确的 Content-Type
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 构建 x-www-form-urlencoded 格式的请求体
            String requestBody = "image=" + java.net.URLEncoder.encode(imageBase64, "UTF-8") +
                    "&id_card_side=" + java.net.URLEncoder.encode(idCardSide, "UTF-8");

            httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String result = EntityUtils.toString(responseEntity);
                    ObjectMapper mapper = new ObjectMapper();
                    return mapper.readValue(result, HashMap.class);
                }
            }
        }
        return null;
    }
}
